<?php
// +----------------------------------------------------------------------
// | 幕小铺
// +----------------------------------------------------------------------
// | 版权所有 2016~2020 幕小铺科技（大连）有限公司
// +----------------------------------------------------------------------
// | 2020/03/14
// +----------------------------------------------------------------------
namespace app\erp\behavior\salecar;

/**
 * 购物车变更库存
 * @package app\user_center\behavior\user
 * @author shiqiang
 */
class updateStock{
    /**
     * 执行行为 run方法是Behavior唯一的接口
     * @access public
     * @return void
     */
    public function run($params){
    	$uid = $params['user_id'];
		
		$map = [];
		$map['uid'] 		= $uid;
		$map['pay_status'] 	= 4;//已过期
		$order_list = model('ErpGoodsOrder') -> withTrashed() -> where($map) -> column('id as order_id,store_id');//已过期的订单
		
		if(!empty($order_list)){
			foreach($order_list as $value){
				$order_id = $value['order_id'];
				$store_id = $value['store_id'];
				
				$map = [];
				$map['order_id'] = $order_id;
				//释放库存
				$sku_list = model('ErpGoodsOrderSkulist') -> where($map) -> column('id,sku_id,num');
				if(!empty($sku_list)){
					//根据门店id 查询出仓库的id
					$warehouse_list = model('ErpStoreWarehouse') -> getStoreWarehouse($store_id);
					foreach ($warehouse_list['data'] as $key => $value) {
						if($value['type'] == 1){//分店仓库
							$store_warehouse_list[] = $value['wid'];
						}
					}
					$warehouse_id 	= $store_warehouse_list[0];//仓库id

					foreach($sku_list as $key => $value){
						$sku_id = $value['sku_id'];
						$num 	= $value['num'];
						
						$map = [];
						$map['sku_id'] 			= $sku_id;
						$map['warehouse_id'] 	= $warehouse_id;
						$sku_info = model('ErpGoodsWarehouseStockNum') -> where($map) -> column('id as stock_id,frozen_num,available_num');//当前库存
						
						//计算库存数
						$frozen_num 	= $sku_info['frozen_num'] - $num; //冻结数 减少
						$available_num 	= $sku_info['available_num'] + $num; //可用库存增加
						$stock_num = $frozen_num + $available_num; //总库存
						
						//插入库存
						$map = [];
						$map['id'] = $sku_info['stock_id'];
						
						$data= [];
						$data['frozen_num'] 	= $frozen_num;
						$data['available_num'] 	= $available_num;
						$data['stock_num'] 		= $stock_num;
						
						$res = model('ErpGoodsWarehouseStockNum') -> update($data, $map);
						if(!$res){
							DB::rollback();
						}
					}
				}
			}
		}
    }
}
